import 'package:flutter_js/flutter_js.dart';
import 'package:flutter/services.dart' show rootBundle;

class JsSignatureGenerator {
  static JavascriptRuntime? _jsRuntime;
  static bool _isInitialized = false;

  static Future<void> initialize() async {
    if (_isInitialized) return;
    
    try {
      // 创建 JavaScript 运行时
      _jsRuntime = getJavascriptRuntime();
      
      // 加载 sign.js 文件
      final jsCode = await rootBundle.loadString('assets/js/sign.js');
      
      // 执行 JavaScript 代码
      final result = _jsRuntime!.evaluate(jsCode);
      
      if (result.isError) {
        print('JavaScript 初始化错误: ${result.stringResult}');
      } else {
        _isInitialized = true;
        print('JavaScript 引擎初始化成功');
      }
    } catch (e) {
      print('初始化 JavaScript 引擎失败: $e');
    }
  }

  static String? generateSignature(String md5Param) {
    if (!_isInitialized || _jsRuntime == null) {
      print('JavaScript 引擎未初始化');
      return null;
    }
    
    try {
      // 调用 JavaScript 中的 get_sign 函数
      final result = _jsRuntime!.evaluate('get_sign("$md5Param")');
      
      if (result.isError) {
        print('JavaScript 执行错误: ${result.stringResult}');
        return null;
      }
      
      return result.stringResult;
    } catch (e) {
      print('调用 JavaScript 函数失败: $e');
      return null;
    }
  }

  static void dispose() {
    _jsRuntime?.dispose();
    _jsRuntime = null;
    _isInitialized = false;
  }
}